#pragma once
#include "../DirectX/stdafx.h"


struct BariersLevel
{
public:
	vector<int>		lengths;

	BariersLevel()
	{
		lengths.clear();
		lengths.resize(9, 100);
	}
	void Nulled()
	{
		lengths.clear();
		lengths.resize(9, 100);
	}

	float GetClearBestPath(D3DXVECTOR2 &dir_path2D)
	{
		//0.69813170079f
		//0.885f

		return 0;
	}

	D3DXVECTOR3 GetPath(time_t Time, const D3DXVECTOR3 &dir_lastPath3D)
	{
		D3DXVECTOR2			dir_lastPath2D(dir_lastPath3D.x, dir_lastPath3D.y);
		D3DXVec2Normalize	(&dir_lastPath2D, &dir_lastPath2D);

		D3DXMATRIX						Rotate;

		D3DXVECTOR4						result(0, 0, 0, 0);

		int								best = -1;
		float							minimum_lengths = 100000;

		for(int q=0; q < lengths.size(); q++)
		{
			D3DXMATRIX						matrix_buffer;
			D3DXVECTOR4						vector_buffer;
			D3DXMatrixIdentity				(&matrix_buffer);
			D3DXMatrixRotationZ				(&matrix_buffer, q * 0.69813170079f);
			D3DXVec3Transform				(&vector_buffer, &D3DXVECTOR3(0, 1, 0), &matrix_buffer);

			D3DXVECTOR2						vector_2D_buffer(vector_buffer.x, vector_buffer.y);
			D3DXVec2Normalize				(&vector_2D_buffer, &vector_2D_buffer);
			
			 
			float	lengths_buffer = sqrt(	abs(vector_2D_buffer.x - dir_lastPath2D.x) * abs(vector_2D_buffer.x - dir_lastPath2D.x) +
											abs(vector_2D_buffer.y - dir_lastPath2D.y) * abs(vector_2D_buffer.y - dir_lastPath2D.y) );

			if(minimum_lengths > lengths_buffer)
			{
				best			= q;
				minimum_lengths = lengths_buffer;
			}
		}

		int								start = 0;
		if(best != -1)
			start = best;

		bool							flag_first = false;

		for(int i_buf=0, q=start, w=9 - start; i_buf<lengths.size(); q++, w--)
		{
			q %= 9;
			if(w < 0)
				w = 8;

			if(lengths[q] == 100 && L_Next(q) == 100 && L_Post(q) == 100)
			{
				D3DXMatrixIdentity				(&Rotate);
				D3DXMatrixRotationZ				(&Rotate, q * 0.69813170079f);// + 0.885f/*GetClearBestPath(dir_lastPath2D)*/ );
				D3DXVec3Transform				(&result, &D3DXVECTOR3(0, 1, 0), &Rotate);
				break;
			}
			

			if(flag_first && lengths[w] == 100 && R_Next(w) == 100 && R_Post(w) == 100)
			{
				D3DXMatrixIdentity				(&Rotate);
				D3DXMatrixRotationZ				(&Rotate, (9 - w) * -0.69813170079f);// - 0.885f/*GetClearBestPath(dir_lastPath2D)*/ );
				D3DXVec3Transform				(&result, &D3DXVECTOR3(0, 1, 0), &Rotate);
				break;
			}

			flag_first = true;
		}
		D3DXVECTOR3			Result;

		Result.x = -result.x;
		Result.y = result.y;
		Result.z = 0;


		return Result;
	}

	int L_Next(int index)
	{
		return lengths[(index + 1) % 9];
	}
	int L_Post(int index)
	{
		index--;
		if(index < 0)
			index = 9;
		return lengths[index];
	}
	int R_Next(int index)
	{
		return L_Post(index);
	}
	int R_Post(int index)
	{
		return L_Next(index);
	}
};